package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("sessions")
public class SessionController {
    @Autowired
    private IUserService userService;

    /**
     * 登录
     *
     * @param email
     * @param password
     * @return
     */
    @PostMapping
    public JSONResult login(@RequestParam String email, @RequestParam String password) {
        JSONResult json = new JSONResult();
        try {
            //验证登录
            User user = userService.login(email, password);
            //将用户存入session
            UserContext.setCurrentUser(user);
            //设置result，方便页面显示
            json.setResult(user);
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    /**
     * 注销
     * @return
     */
    @DeleteMapping
    public JSONResult logout() {
        JSONResult json = new JSONResult();
        UserContext.getSession().invalidate();
        return json;
    }
}
